import Tips from './Tips';

/**
 * 授权认证
 * 
 * @export
 * @class OAuth
 */
export default class OAuth {
    /**
     * 获取登录授权认证并登录
     *
     * @static
     * @memberof OAuth
     */
    static login() {
        return new Promise((resolve, reject) => {
            plus.oauth.getServices(services => {
                const items = services.map(item => {
                    return {
                        title: item.description
                    };
                });
                Tips.action('登录', items)
                    .then(index => {
                        const service = services[index - 1];
                        service.login(e => {
                            var result = e.target.authResult;
                            resolve(result);
                        }, error => {
                            reject(error);
                        });
                    });
            }, error => {
                reject(error);
            });
        });
    }

    /**
     * 注销登录授权认证
     *
     * @static
     * @memberof OAuth
     */
    static logout() {
        return new Promise((resolve, reject) => {
            plus.oauth.getServices(services => {
                for (const key in services) {
                    if (services.hasOwnProperty(key)) {
                        const service = services[key];
                        if (service.authResult) {
                            service.logout(e => {
                                Tips.alert("注销登录认证成功！");
                            }, e => {
                                Tips.alert("注销登录认证失败！");
                            });
                        }
                    }
                }
                resolve();
            }, error => {
                reject(error);
            });
        });
    }
}